from selenium import webdriver as wd
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.switch_to import SwitchTo
from selenium.webdriver.support.ui import Select
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from typing import List

from config import config
current_iframe: any = None
mainFrame = ["mainFrame"]
dialogiframe = ["dialogiframe"]
dialogiframe1 = ["dialogiframe1"]
dialogiframe1_auditIframe = ["dialogiframe1","auditIframe"]
dialogiframe1_processIframe = ["dialogiframe1","processIframe"]
dialogiframe1_processIframe_subFrame = ["dialogiframe1","processIframe","subFrame"]
auditlframe = ["dialogiframe","auditIframe"]
dialogiframe2 = ["dialogiframe2"]

def switch_frame(driver: wd.Chrome,frame: List[str]):
    global mainFrame
    global dialogiframe
    global auditlframe
    driver.switch_to.default_content()
    for frameId in frame:
        target_frame = driver.find_element(By.ID,frameId)
        driver.switch_to.frame(target_frame)
        print("切换frame成功，当前frameId=",frameId)
    


def change_iframe(driver: wd.Chrome, iframe_id):
    global current_iframe
    if current_iframe :
        print()
        #print("切换前的iframe_id",current_iframe.get_attribute('id'))
    iframe = driver.find_element(By.ID,iframe_id)
    current_iframe = iframe
    ##EC.frame_to_be_available_and_switch_to_it(By.ID,iframe_id)
    driver.switch_to.frame(iframe)
    print("当前iframeid",iframe.get_attribute('id'))
    #print("切换后的iframe_id",current_iframe.get_attribute('id'))
   
def change_iframe_by_path(driver: wd.Chrome,path):
    iframe = driver.find_element(By.XPATH,path)
    print("当前iframeid",iframe.get_attribute('id'))
    driver.switch_to.frame(iframe)

def change_iframe_until_loaded(driver: wd.Chrome,iframe_id):
    wait = WebDriverWait(driver, 10)

    # 定位 iframe 元素
    iframe_locator = (By.ID, iframe_id)

    # 等待 iframe 加载完成
    iframe = wait.until(EC.presence_of_element_located(iframe_locator))

    # 切换到 iframe 上下文
    driver.switch_to.frame(iframe)
#第一次切换iframe之前current_iframe为 NONE
def get_current_iframe(driver: wd.Chrome):
    global current_iframe
    iframe = driver.current_url
    #iframe_id_attribute = iframe_id.__getattribute__('id')
    return current_iframe
    print("iframe切换成功，当前iframe",iframe_id_attribute)

def time_sleep(time_delay):
        print("等待...")
        time.sleep(time_delay)
def find_element(driver: wd.Chrome,by: By,path: str):
    ele = driver.find_element(by,path)
    time.sleep(config.delay_time)
    return ele
def find_elements_in_html(driver: wd.Chrome,str: str):
    elements = driver.find_elements(By.XPATH,f"//*[contains(text(), '{str}')]")

    return elements